package cn.matezk.lianlian.controller;

import cn.hutool.json.JSONUtil;
import cn.matezk.lianlian.service.IWechatService;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.iotexplorer.v20190423.IotexplorerClient;
import com.tencentcloudapi.iotexplorer.v20190423.models.ControlDeviceDataRequest;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.bean.menu.WxMenu;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.menu.WxMpMenu;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;

@RestController
@RequestMapping("wechat")
@Slf4j
public class WechatController {
    @Autowired
    private IWechatService wechatService;
    @Autowired
    private WxMpService wxMpService;
    @Value("${tencent.endpoint}")
    private String endpoint;
    @Value("${tencent.region}")
    private String region;
    @Value("${tencent.secret-id}")
    private String secretId;
    @Value("${tencent.secret-key}")
    private String secretKey;
    @Value("${tencent.notify-device}")
    private String notifyDevice;

    @GetMapping
    public String check(@RequestParam String timestamp,
                        @RequestParam String nonce,
                        @RequestParam String signature,
                        @RequestParam String echostr) throws IOException {
        Boolean flag = wxMpService.checkSignature(timestamp, nonce, signature);
        return Boolean.TRUE.equals(flag) ? echostr : "";
    }

    @PostMapping
    public void push(@RequestBody String payload) throws WxErrorException {
        WxMpXmlMessage message = WxMpXmlMessage.fromXml(payload);
        if ("subscribe".equals(message.getEvent())) {
            ttsPlay("用户关注公众号");
            wechatService.subscribe(message.getFromUser());
        } else if ("unsubscribe".equals(message.getEvent())) {
            ttsPlay("用户取关公众号");
            wechatService.unsubscribe(message.getFromUser());
        } else if ("text".equals(message.getMsgType())) {
            ttsPlay(message.getContent());
        }
    }

    @GetMapping("syncUser")
    public Boolean selector() throws WxErrorException {
        wechatService.syncUsers();
        return Boolean.TRUE;
    }

    @PostMapping("menus")
    public Boolean menus(@RequestBody WxMenu menu) throws WxErrorException {
        wxMpService.getMenuService().menuCreate(menu);
        return Boolean.TRUE;
    }

    @GetMapping("menus")
    public WxMpMenu menus() throws WxErrorException {
        return wxMpService.getMenuService().menuGet();
    }

    private void ttsPlay(String text) {
        HttpProfile httpProfile = new HttpProfile();
        httpProfile.setEndpoint(endpoint);
        ClientProfile clientProfile = new ClientProfile();
        clientProfile.setHttpProfile(httpProfile);
        Credential credential = new Credential(secretId, secretKey);
        ControlDeviceDataRequest request = new ControlDeviceDataRequest();
        request.setProductId(notifyDevice.split("/")[0]);
        request.setDeviceName(notifyDevice.split("/")[1]);
        request.setData(JSONUtil.createObj()
                .set("text", "微信消息:".concat(text))
                .set("times", 1).toString());
        try {
            IotexplorerClient client = new IotexplorerClient(credential, region, clientProfile);
            client.ControlDeviceData(request);
        } catch (Exception e) {
            log.info(e.getMessage());
        }
    }
}
